<script setup>
import { useRouter, useRoute } from 'vue-router';
import { watch, ref } from 'vue';

const router = useRouter();
const route = useRoute();
const keyword = ref(route.query.keyword || '');

watch(() => route.query.keyword, (value) => {
    keyword.value = value || '';
});

function handleSearch() {
    const path = route.path;
    const newQuery = { ...route.query, keyword: keyword.value };
    router.push({ path, query: newQuery });
}

function handleClear() {
    keyword.value = '';
    const path = route.path;
    const newQuery = { ...route.query, keyword: '' };
    router.push({ path, query: newQuery });
}
</script>

<template>
    <div class="search">
        <el-input v-model="keyword" placeholder="请输入关键字" @keyup.enter.native="handleSearch" @clear="handleClear" clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
    </div>
</template>

<style scoped>
.search {
    width: 240px;
}
</style>